import React, { Component } from 'react';
import constant from "../constant";
import SettingService from "../setting-service";
import { Button, Form, message, Switch } from "antd";
import DateRangePicker from 'components/date-range-picker'
import moment from "moment";
import { messages } from "share/common";
import Chooser from "components/chooser";

class AuthorizationRule extends Component {

  state = {
    saveLoading: false,
    extraParams: {}
  };

  componentDidMount() {
    const { record } = this.props.params;
    if (record.id) {
      this.setState({ extraParams: { companyId: record.companyId, departmentId: record.departmentId } })
    }
  }

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        this.setState({ saveLoading: true });
        const { record, id } = this.props.params, { close, accountType } = this.props;
        value.authorizeDateFrom = new Date(value.authorizeDate[0]).format('yyyy-MM-dd');
        value.authorizeDateTo = value.authorizeDate[1] ? new Date(value.authorizeDate[1]).format('yyyy-MM-dd') : undefined;
        delete value.authorizeDate;
        value.bankAccountId = id;
        value.authorizeCompanyId = value.authorizeCompanyId[0].id;
        if (value.authorizeDepartmentId[0]) {
          value.authorizeDepartmentId = value.authorizeDepartmentId[0].id;
        }  else {
          value.authorizeDepartmentId = null;
        }
        if (value.authorizeEmployeeId[0]) {
          value.authorizeEmployeeId = value.authorizeEmployeeId[0].userOid;
        } else {
          value.authorizeEmployeeId = null;
        }
        if (!value.authorizeDepartmentId) {
          value.authFlag = 1001;
        } else {
          if (!value.authorizeEmployeeId) {
            value.authFlag = 1002;
          } else {
            value.authFlag = 1003;
          }
        }
        value.accountType = accountType;
        SettingService.saveAuthorization(Object.assign(record, value)).then(() => {
          this.setState({ saveLoading: false }, () => {
            message.success(messages('common.operate.success')/*操作成功*/);
            close(true);
          });
        }).catch(e => {
          message.error(e.response.data.message);
          this.setState({ saveLoading: false });
        })
      }
    })
  };

  handleCompany = value => {
    let { extraParams } = this.state;
    extraParams.companyId = (value || []).length ? value[0].id : undefined;
    this.setState({ extraParams });
    this.props.form.setFieldsValue({
      authorizeEmployeeId: []
    });
  };

  handleDepartment = value => {
    let { extraParams } = this.state;
    extraParams.departmentId = (value || []).length ? value[0].id : undefined;
    this.setState({ extraParams });
    this.props.form.setFieldsValue({
      authorizeEmployeeId: []
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { saveLoading, extraParams } = this.state;
    const { formItemLayout } = constant;
    const { close } = this.props, { record } = this.props.params;
    return(
      <div>
        <Form className={'new-form'}>
          <Form.Item
            label={messages('common.column.status')/*状态*/}
            {...formItemLayout}
          >
            {getFieldDecorator("enabled", {
              rules: [{ required: true }],
              valuePropName: "checked",
              initialValue: record.hasOwnProperty('enabled') ? record.enabled : true
            })(
              <Switch>{messages('finance-1.key244')/*启用temp*/}</Switch>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key360')/*有效日期*/}
            {...formItemLayout}
          >
            {getFieldDecorator("authorizeDate", {
              rules: [
                { required: true, message: messages('finance-1.key361')/*起始时间必填*/ },
                {
                  validator: (item, value, callback) => {
                    if (!value[0]) {
                      callback(messages('common.please.input')/*请输入*/);
                    }
                    callback();
                  }
                }
              ],
              initialValue: Object.keys(record).length > 0 ?
                (record.authorizeDateTo ? [moment(record.authorizeDateFrom), moment(record.authorizeDateTo)] : [moment(record.authorizeDateFrom)]) : []
            })(
              <DateRangePicker
                placeholder={messages('finance-1.key362')/*请选择日期范围*/}
                allowClear
                getRadios={() => [{
                  text: messages('finance-1.key363')/*本月*/,
                  startDate: moment(),
                  endDate: moment(moment().format('YYYY-MM-DD')).endOf('month')
                }, {
                  text: messages('finance-1.key364')/*3个月*/,
                  startDate: moment(),
                  endDate: moment().subtract(-3, 'month')
                }, {
                  text: messages('finance-1.key365')/*6个月*/,
                  startDate: moment(),
                  endDate: moment().subtract(-6, 'month')
                }]}
              />
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key366')/*被授权公司*/}
            {...formItemLayout}
          >
            {getFieldDecorator("authorizeCompanyId", {
              rules: [{ required: true, message: messages('common.select')/*请选择*/ }],
              initialValue: Object.keys(record).length > 0 ? [{ id: record.companyId, name: record.companyName }] : []
            })(
              <Chooser
                placeholder={messages('common.select')/*请选择*/}
                type="available_company"
                labelKey="name"
                valueKey="id"
                single
                onChange={this.handleCompany}
              />
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key367')/*被授权部门*/}
            {...formItemLayout}
          >
            {getFieldDecorator("authorizeDepartmentId", {
              initialValue:  record.departmentId ? [{ id: record.departmentId, name: record.departmentName }] : []
            })(
              <Chooser
                placeholder={messages('common.select')/*请选择*/}
                type="journal_line_department"
                labelKey="name"
                valueKey="id"
                single
                onChange={this.handleDepartment}
              />
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key318')/*被授权员工*/}
            {...formItemLayout}
          >
            {getFieldDecorator("authorizeEmployeeId", {
              initialValue: record.authorizeEmployeeId ? [{ userOid: record.authorizeEmployeeId, userName: record.employeeName }] : []
            })(
              <Chooser
                placeholder={messages('common.select')/*请选择*/}
                type="select_authorization_user"
                labelKey="userName"
                valueKey="userOid"
                single
                listExtraParams={extraParams}
              />
            )}
          </Form.Item>
          <div className='footer-operate'>
            <Button type='primary' onClick={this.handleSave} loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
            <Button onClick={() => close()}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

export default Form.create()(AuthorizationRule)
